package datatypes;

import java.util.Vector;

public class PicoNet {
	private static int lastPiconetID = 0;
	private int maxNumberMember = 8;

	private Vector<Host> members = new Vector<Host>();
	private int piconetID = -1;
	private HostDescription master = null;
	private boolean isAlive = false;
	private int centerX = -1;
	private int centerY = -1;
	private int distance = -1;

	public PicoNet(int distance) {
		this.distance = distance;
	}

	public void launchPiconet(HostDescription master, int maxMember) {
		this.master = master;
		this.maxNumberMember = maxMember;
		centerX = master.getX();
		centerY = master.getY();
		this.piconetID = lastPiconetID + 1;
		lastPiconetID = this.piconetID;
		isAlive = true;
	}

	public boolean isPossibleMember(int posx, int posy) {
		if (this.members.size() < maxNumberMember) {

			if (isAlive) {
				int tempx = Math.abs(this.centerX) - Math.abs(posx);
				int tempy = Math.abs(this.centerY) - Math.abs(posy);
				if (distance < pythagorasDistance((double) tempx,
						(double) tempy)) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	private double pythagorasDistance(double lengthKath1, double lengthKath2) {
		return Math.sqrt((lengthKath1 * lengthKath1)
				+ (lengthKath2 * lengthKath2));
	}

	public HostDescription getMaster(){
		return this.master;
	}
	public boolean isMaster (int hostID){
		for (int i = 0; i < members.size(); i++){
			if (this.isAlive && master.getHost().isEqual(hostID)){
				return true;
			}
		}
		return false;
	}
	public boolean isMember(int hostID) {
		for (int i = 0; i < members.size(); i++) {
			if (members.get(i).isEqual(hostID)) {
				return true;
			}
		}
		return false;
	}

	public void killPiconet() {
		this.isAlive = false;
		master = null;
		centerX = -1;
		centerY = -1;
		distance = -1;
	}

	public boolean quitMembership(int hostId) {
		if (this.master == null || this.master.getHost().isEqual(hostId)) {
			this.killPiconet();
			return true;
		} else {
			for (int i = 0; i < members.size(); i++) {
				if (members.get(i).isEqual(hostId)) {
					members.remove(i);
					return true;
				}
			}
			return false;
		}
	}

	public boolean join(HostDescription newMember) {
		if (this.isAlive
				&& this.isPossibleMember(newMember.getX(), newMember.getY())) {
			members.add(newMember.getHost());
			return true;
		}
		return false;
	}
	
	public int getPiconetId(){
		return this.piconetID;
	}
}
